package com.tongtech.system.service.impl;

import com.tongtech.common.core.utils.DateUtils;
import com.tongtech.common.core.utils.StringUtils;
import com.tongtech.system.api.domain.SysDept;
import com.tongtech.system.api.domain.SysUser;
import com.tongtech.system.domain.Customer;
import com.tongtech.system.domain.Project;
import com.tongtech.system.domain.vo.ProjectValue;
import com.tongtech.system.enums.ProjectStatusType;
import com.tongtech.system.mapper.ProjectMapper;
import com.tongtech.system.service.ICustomerService;
import com.tongtech.system.service.IProjectService;
import com.tongtech.system.service.ISysUserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;

/**
 * 项目管理 服务实现
 *
 * @author xingyc
 */
@Service
public class ProjectServiceImpl implements IProjectService {
    @Autowired
    private ProjectMapper projectMapper;

    @Autowired
    private ISysUserService userService;

    @Autowired
    private ICustomerService customerService;

    /**
     * 查询项目管理数据
     *
     * @param project 项目信息
     * @return 项目信息集合
     */
    @Override
    public List<Project> selectProjectList(Project project) {
        List<Project> list = projectMapper.selectProjectList(project);

        return list;
    }

    /**
     * 根据项目ID查询信息
     *
     * @param projectId 项目ID
     * @return 项目信息
     */
    @Override
    public Project selectProjectById(Long projectId) {
        Project project = projectMapper.selectProjectById(projectId);
        Long customerId = project.getCustomerId();
        Long marketerId = project.getMarketerId();
        if (Objects.nonNull(customerId)) {
            Customer customer = customerService.selectCustomerById(customerId);
            if (customer != null) {
                String name = customer.getName();
                project.setCustomerName(name);
            }
        }
        if (Objects.nonNull(marketerId)) {
            SysUser user = userService.selectUserById(marketerId);
            if (user != null) {
                String nickName = user.getNickName();
                project.setMarketerName(nickName);

                SysDept dept = user.getDept();
                String deptName = dept.getDeptName();
                project.setMarketerDeptName(deptName);
            }
        }
        //将开始和结束时间转换成dateRange
        setDateRange(project);
        return project;
    }
    private void setDateRange(Project project){
        Date startMaintenanceDate = project.getStartMaintenanceDate();
        if(Objects.nonNull(startMaintenanceDate)){
            Date endTime = project.getEndMaintenanceDate();
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            String start = sdf.format(startMaintenanceDate);
            String end = sdf.format(endTime);
            String[] dateRange = new String[]{start, end};
            project.setDateRange(dateRange);
        }
    }

    @Override
    public Map<String, List> selectProjectBasicInfoById(Long projectId) {
        Project project = selectProjectById(projectId);
        if (Objects.nonNull(project)) {
            Map<String, List> map = new ConcurrentHashMap<>();
            List projectInfo = new ArrayList<>();
            List applicantInfo = new ArrayList<>();
            //项目编号
            String projectNo = project.getProjectNo();
            if (StringUtils.isNotEmpty(projectNo)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("项目编号");
                projectNoValue.setValue(projectNo);
                projectInfo.add(projectNoValue);
            }
            //项目状态
            String projectStatus = project.getProjectStatus();
            if (Objects.nonNull(projectStatus)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("项目状态");
                projectNoValue.setValue(Objects.equals(ProjectStatusType.UNSIGNED.getCode(), projectStatus) ? "未签" : "已签");
                projectInfo.add(projectNoValue);
            }
            //根据维保日期，计算维保状态。若当前日期超过维保结束日期，则过保
            Date endMaintenanceDate = project.getEndMaintenanceDate();
            if (Objects.nonNull(endMaintenanceDate)) {
                long endTime = endMaintenanceDate.getTime();
                long currentTime = System.currentTimeMillis();
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("维保情况");
                if (currentTime - endTime > 0) {
                    projectNoValue.setValue("已过保");
                } else {
                    projectNoValue.setValue("未过保");
                }

                ProjectValue endDateValue = new ProjectValue();
                endDateValue.setTitle("维保结束时间");
                endDateValue.setValue(DateUtils.dateTime(endMaintenanceDate));

                projectInfo.add(projectNoValue);
                projectInfo.add(endDateValue);
            }
            //维保开始日期
            Date startMaintenanceDate = project.getStartMaintenanceDate();
            if (Objects.nonNull(startMaintenanceDate)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("维保开始时间");
                projectNoValue.setValue(DateUtils.dateTime(startMaintenanceDate));
                projectInfo.add(projectNoValue);
            }

            Integer contractDays = project.getContractDays();
            if (Objects.nonNull(contractDays)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("合同现场人天数");
                projectNoValue.setValue(String.valueOf(contractDays));
                projectInfo.add(projectNoValue);
            }
            Integer residueDays = project.getResidueDays();
            if (Objects.nonNull(residueDays)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("剩余现场人天数");
                projectNoValue.setValue(String.valueOf(contractDays));
                projectInfo.add(projectNoValue);
            }
            String marketerName = project.getMarketerName();
            if (Objects.nonNull(marketerName)) {
                ProjectValue projectNoValue = new ProjectValue();
                projectNoValue.setTitle("销售负责人");
                projectNoValue.setValue(marketerName);

                projectInfo.add(projectNoValue);

                ProjectValue applicantValue = new ProjectValue();
                applicantValue.setTitle("申请人");
                applicantValue.setValue(marketerName);

                applicantInfo.add(applicantValue);
            }

            map.put("projectData", projectInfo);

            String deptName = project.getMarketerDeptName();
            if (Objects.nonNull(deptName)) {
                ProjectValue applicantValue = new ProjectValue();
                applicantValue.setTitle("所属部门");
                applicantValue.setValue(deptName);
                applicantInfo.add(applicantValue);
            }

            ProjectValue applicantValue = new ProjectValue();
            applicantValue.setTitle("单位主体");
            applicantValue.setValue("东方通软件");
            applicantInfo.add(applicantValue);

            map.put("applicantData", applicantInfo);
            return map;
        }
        return null;
    }

    private void formatStartEndTime(String[] dataRange, Project project) {
        if (dataRange != null && dataRange.length > 0) {
            String startDate = dataRange[0];
            String endDate = dataRange[1];
            SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
            try {
                project.setStartMaintenanceDate(sdf.parse(startDate));
                project.setEndMaintenanceDate(sdf.parse(endDate));
            } catch (ParseException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 新增保存项目信息
     *
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public int insertProject(Project project) {
        if (Objects.nonNull(project)) {
            String[] dataRange = project.getDateRange();
            formatStartEndTime(dataRange, project);
            //默认contractDays和residueDays相等，支持一次扣一次。
            Integer contractDays = project.getContractDays();
            if(Objects.nonNull(contractDays)){
                project.setResidueDays(contractDays);
            }
        }
        return projectMapper.insertProject(project);
    }

    /**
     * 修改保存项目信息
     *
     * @param project 项目信息
     * @return 结果
     */
    @Override
    public int updateProject(Project project) {
        if (Objects.nonNull(project)) {
            String[] dataRange = project.getDateRange();
            formatStartEndTime(dataRange, project);
        }
        int result = projectMapper.updateProject(project);
        return result;
    }

    /**
     * 删除项目管理信息
     *
     * @param deptId 项目ID
     * @return 结果
     */
    @Override
    public int deleteProjectById(Long deptId) {
        return projectMapper.deleteProjectById(deptId);
    }
}
